import { h, ref, watch, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { NSpace, NTooltip, NButton, NIcon } from 'naive-ui'
import { EditOutlined } from '@vicons/antd'
import {
  COLUMN_WIDTH_CONFIG,
  calculateTableWidth,
  DefaultTableWidth
} from '@/common/column-width-config'
import { InternalRowData, TableColumns } from '@/common/types'
import { Database } from '@vicons/fa'

export function useColumns(onCallback: Function) {
  const t = window.$t

  const columnsRef = ref({
    columns: [] as TableColumns,
    tableWidth: DefaultTableWidth
  })

  const createColumns = () => {
    const columns = [
      {
        title: '#',
        key: 'index',
        align: 'center',
        render: (rowData: InternalRowData, rowIndex: number) => rowIndex + 1,
        ...COLUMN_WIDTH_CONFIG['index']
      },
      {
        title: t('dataManage.dbName'),
        key: 'dbName',
        align: 'center',
        className: 'name',
        ...COLUMN_WIDTH_CONFIG['name']
      },
      {
        title: t('dataManage.remark'),
        key: 'remark',
        align: 'center',
        ...COLUMN_WIDTH_CONFIG['name']
      },
      {
        title: t('dataManage.owner'),
        key: 'owner',
        align: 'center',
        width: 150
      },
      {
        title: t('dataManage.tableList'),
        align: 'center',
        width: 80,
        render: (rowData: any, unused: number) =>
          h(
            NTooltip,
            {
              trigger: 'hover'
            },
            {
              trigger: () =>
                h(
                  NButton,
                  {
                    circle: true,
                    type: 'warning',
                    size: 'small',
                    onClick: () =>
                      void onCallback({ rowData }, 'openTableListTab')
                  },
                  {
                    icon: () => h(NIcon, null, () => h(Database))
                  }
                ),
              default: () => t('dataManage.tableList')
            }
          )
      },
      {
        title: t('common.operation'),
        key: 'operation',
        align: 'center',
        ...COLUMN_WIDTH_CONFIG['operation'](1),
        render: (rowData: any, unused: number) => {
          return h(NSpace, null, {
            default: () => [
              h(
                NButton,
                {
                  onClick: () => void onCallback({ rowData }, 'syncDbMeta'),
                  quaternary: true,
                  type: 'info',
                  size: 'small'
                },
                t('dataManage.syncMeta')
              )
            ]
          })
        }
      }
    ] as TableColumns

    columnsRef.value = {
      columns,
      tableWidth: calculateTableWidth(columns)
    }
  }

  onMounted(() => {
    createColumns()
  })

  watch(useI18n().locale, () => {
    createColumns()
  })

  return {
    columnsRef,
    createColumns
  }
}
